package cn.codeforfun.cloud.center.client.core;

import cn.codeforfun.cloud.center.client.constants.ClientProperties;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;

@Slf4j
public class CloudClient {

    public void start(ClientProperties properties, Environment environment) {
        startHealthSchedule(properties, environment);
    }

    /**
     * 开始发送健康信息
     */
    public void startHealthSchedule(ClientProperties properties, Environment environment) {
        CronUtil.schedule("0/30 * * * * *", (Task) () -> {
            String applicationName = environment.getProperty("spring.application.name");
            if (ObjectUtils.isEmpty(applicationName)) {
                applicationName = "UNKNOWN";
            }
            HashMap<String, Object> parameter = new HashMap<>();
            parameter.put("applicationName", applicationName);

            String url = "http://" + properties.getHost() + ":" + properties.getPort() + "/api/register";
            HttpResponse response = null;
            String body = null;
            try {
                body = JSONUtil.toJsonStr(parameter);
                response = HttpUtil.createPost(url).body(body, MediaType.APPLICATION_JSON_VALUE).execute();
            } catch (Exception e) {

                String message = "ConnectException: Connection refused (Connection refused)";
                if (message.equals(e.getMessage())) {
                    log.error(message + " #### url:{}, body:{}", url, body);
                } else {
                    log.error(e.getMessage());
                }
            }
            if (response != null && !response.isOk()) {
                log.error("register error,status:{},body:{}", response.getStatus(), response.body());
            }
        });

        CronUtil.setMatchSecond(true);
        CronUtil.start();
    }
}
